package com.mojo.jedis.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 *
 * @author <a href="mailto:shujinjing@bmos.net.cn">Mojo</a>
 */
@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 基于SetNX和Expire设置redis分布式锁
     * 自定义实现redis分布式锁
     */
    public Boolean tryLock(String key, String value, int expireTime) {
        // 同时用setnx和expire设置key的value和过期时间，保证原子性
        return redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, TimeUnit.SECONDS);

    }
    public void unlock(String key) {
        redisTemplate.delete(key);
    }
}
